import React, { Component, Suspense } from 'react'
import { Redirect, Route, Switch } from "react-router-dom"
import routeList, { defaultRouteKey } from '../route';
import Loading from '../../pages/Loading';

export default class AutoRoute extends Component {
  filterComponentRoute = (handleList, preList = []) => {
    handleList.forEach(item => {
      if (item.component) preList.push(item)
      if (item.children) this.filterComponentRoute(item.children, preList)
    });
    return preList;
  }
  render() {
    const componentRouteList = this.filterComponentRoute(routeList);
    // console.log('componentRouteList', componentRouteList);
    return (
      <div style={{width: '100%', height: '100%', overflow: 'auto'}}>
        <Suspense fallback={<Loading/>}>
          <Switch>
            {
              componentRouteList.map(item => {
                // Route匹配path时，在匹配成功后，会继续向下匹配直到遍历完。所以若多个Route的path相同，component不同，会以最后一个为准。
                // switch组件就能解决此问题
                return <Route key={item.key} exact={item.children ? true : false} path={item.key} component={item.component}></Route>
              })
            }
            {/* Redirect必须写在每组Route组件的最后(注：可在在不同组件中注册路由，会由页面出现顺序进行注册) */}
            <Redirect to={defaultRouteKey} />
          </Switch>
        </Suspense>
      </div>
    )
  }
}
